<?php

namespace App\Services\Common;

use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterSheet;
use PhpOffice\PhpSpreadsheet\Cell\DataValidation;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class DownloadTemp implements FromCollection,  WithEvents, WithStyles
{

    //公共模板下载
    private $row;
    private $options;
    private $datawith;
    public function __construct(array $row, array $options = [], array $datawith = [])
    {
        $this->row = $row;
        $this->options = $options;
        $this->datawith = $datawith;
    }


    /**
     * @return \Illuminate\Support\Collection
     */
    public function collection()
    {
        $row = $this->row;

        return collect($row);
    }
    public function registerEvents(): array
    {
        return [
            AfterSheet::class => function (AfterSheet $event) {
                foreach ($this->options as $key => $val) {
                    $event->sheet->getDataValidation($key . '2:' . $key . '1000')->setType(DataValidation::TYPE_LIST)->setShowDropDown(true)->setFormula1(sprintf('"%s"', implode(',', $val)));
                }
            },
        ];
    }

    public function styles(Worksheet $sheet)
    {
       if (count($this->datawith)) {
           foreach ($this->datawith as $key => $val) {
               $sheet->getColumnDimension($key)->setWidth($val);
           }
       }
    }

}
